﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BrainTechLLC.EmlenMud.Communication;
using BrainTechLLC;
using BrainTechLLC.ThreadSafeObjects;
using System.Net;
using System.Threading;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using BrainTechLLC.Communications;

namespace WpfImageReceiver
{
    public class Communications : BaseNotifyPropertyChanged 
    {
        const int PortNum = 4006;
        OutgoingConnection _connectionToServer;

        protected bool _connected;
        protected string _host = "192.168.0.106";
        
        public string HostName
        {
            get { return _host; }
            set
            {
                if (_host != value)
                {
                    _host = value;
                    OnPropertyChanged("HostName");
                }
            }
        }

        public ThreadSafeQueue<Bitmap> IncomingBitmapQueue = new ThreadSafeQueue<Bitmap>();

        public Communications()
        {
        }

        public bool Connected
        {
            get { return _connected; }
            set
            {
                if (_connected != value)
                {
                    _connected = value;
                    OnPropertyChanged("Connected");
                }
            }
        }
        
        public bool IsConnected()
        {
            if (_connectionToServer.NeedsClosing || _connectionToServer.TcpClientConnection == null ||
                _connectionToServer.TcpClientConnection.Socket == null || !_connectionToServer.TcpClientConnection.Socket.Connected)
            {
                Connected = false;
                return false;
            }

            Connected = true;
            return true;
        }

        public bool TryConnect()
        {
            // Connect outgoing thread to the server
            bool success = _connectionToServer.Connect(HostName, PortNum, true);

            // Give the listener some time since there may be a concurrent new connection limit 
            Thread.Sleep(20);

            if (success)
            {
                Connected = true;
            }

            return success;
        }

        public bool Startup(bool tryConnect)
        {
            _connectionToServer = new OutgoingConnection(connectionToServer_MessageReceived);
            if (tryConnect)
            {
                return TryConnect();
            }
            else
            {
                return false;
            }
        }

        public void connectionToServer_MessageReceived(object sender, ObjectEventArgs<ICommunicationsMessage> e)
        {
            byte[] bytes = e.obj.MessageContents as byte[];

            if (bytes == null)
            {
                throw new Exception("Null byte array");
            }

            Bitmap bm = ExtractImageFromBytes(bytes);
            if (bm != null)
            {
                // TODO
                if (IncomingBitmapQueue.Count > 10)
                {
                    IncomingBitmapQueue.Clear();
                }
                IncomingBitmapQueue.Enqueue(bm);
            }
        }

        public Bitmap ExtractImageFromBytes(byte[] rgBytes)
        {
            Bitmap img = null;
            MemoryStream ms = new MemoryStream(rgBytes);
            ms.Seek(0, SeekOrigin.Begin);
            try { img = (Bitmap)Image.FromStream(ms); }
            catch { }
            return img;
        }
    }
}
